#include <iostream>
#include <random>
#include <cstring>
#include <dds/dds.h>
#include "start_atomic_0817_initialize_configuration_service.h" // IDL生成的C语言头文件
#include "../../../include/log_client/LogClient.h"

// DDS实体句柄
static dds_entity_t participant;
static dds_entity_t topic;
static dds_entity_t publisher;
static dds_entity_t writer;

// 清理DDS资源
static void cleanup()
{
    if (writer != DDS_HANDLE_NIL)
        dds_delete(writer);
    if (publisher != DDS_HANDLE_NIL)
        dds_delete(publisher);
    if (topic != DDS_HANDLE_NIL)
        dds_delete(topic);
    if (participant != DDS_HANDLE_NIL)
        dds_delete(participant);
}

// 生成随机配置服务输入数据
start_atomic_0817_initialize_configuration_service_InitConfigInput generate_random_config_data()
{
    // 静态随机数生成器（确保全局只初始化一次）
    static std::mt19937 rng(std::random_device{}());
    std::uniform_int_distribution<int> config_id_dist(1, 999); // 配置文件ID
    std::uniform_int_distribution<int> mode_dist(0, 2);       // 运行模式索引
    std::bernoulli_distribution log_dist(0.5);                // 50%概率启用日志

    // 运行模式选项
    const char* run_modes[] = {"auto", "manual", "test"};

    // 初始化结构体
    start_atomic_0817_initialize_configuration_service_InitConfigInput data;
    
    // 生成随机配置文件路径（需手动管理内存）
    int config_id = config_id_dist(rng);
    std::string config_path = "/config/init_config_" + std::to_string(config_id) + ".json";
    data.config_file_path = strdup(config_path.c_str());

    // 随机选择运行模式
    int mode_idx = mode_dist(rng);
    data.run_mode = strdup(run_modes[mode_idx]);

    // 随机生成日志启用状态
    data.enable_logging = log_dist(rng);

    return data;
}

// 释放配置数据中的字符串内存
static void free_config_data(start_atomic_0817_initialize_configuration_service_InitConfigInput& data)
{
    if (data.config_file_path)
    {
        free(data.config_file_path);
        data.config_file_path = nullptr;
    }
    if (data.run_mode)
    {
        free(data.run_mode);
        data.run_mode = nullptr;
    }
}

int main()
{
    // 初始化日志
    LogClient::getInstance().init("mock_atomic_0817_initialize_configuration_service","mock_atomic_0817_initialize_configuration_service");

    dds_return_t rc;

    // 1. 初始化DDS参与者（DomainParticipant）
    participant = dds_create_participant(DDS_DOMAIN_DEFAULT, NULL, NULL);
    if (participant < 0)
    {
        std::cerr << "错误：创建参与者失败，原因：" << dds_strretcode(-participant) << std::endl;
        LogClient::getInstance().logError("创建参与者失败，原因：" + std::string(dds_strretcode(-participant)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 2. 创建主题（Topic），名称需与订阅者一致
    topic = dds_create_topic(
        participant,
        &start_atomic_0817_initialize_configuration_service_InitConfigInput_desc, // IDL生成的类型描述
        "start_atomic_0817_initialize_configuration_service",                      // 主题名称（必须与订阅者一致）
        NULL, NULL);
    if (topic < 0)
    {
        std::cerr << "错误：创建主题失败，原因：" << dds_strretcode(-topic) << std::endl;
        LogClient::getInstance().logError("创建主题失败，原因：" + std::string(dds_strretcode(-topic)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 3. 创建发布者（Publisher）
    publisher = dds_create_publisher(participant, NULL, NULL);
    if (publisher < 0)
    {
        std::cerr << "错误：创建发布者失败，原因：" << dds_strretcode(-publisher) << std::endl;
        LogClient::getInstance().logError("创建发布者失败，原因：" + std::string(dds_strretcode(-publisher)));
        cleanup();
        return EXIT_FAILURE;
    }

    dds_qos_t *qos = dds_create_qos();
    dds_qset_reliability(qos, DDS_RELIABILITY_RELIABLE, DDS_SECS(10));
    dds_qset_history(qos, DDS_HISTORY_KEEP_LAST, 10);

    // 4. 创建数据写入器（DataWriter）
    writer = dds_create_writer(publisher, topic, qos, NULL);
    if (writer < 0)
    {
        std::cerr << "错误：创建写入器失败，原因：" << dds_strretcode(-writer) << std::endl;
        LogClient::getInstance().logError("创建写入器失败，原因：" + std::string(dds_strretcode(-writer)));
        cleanup();
        return EXIT_FAILURE;
    }
    dds_delete_qos(qos);

    std::cout << "DDS配置服务数据发布者已启动，开始发送数据..." << std::endl;
    LogClient::getInstance().logInfo("DDS配置服务数据发布者已启动，开始发送数据...");

    // 5. 循环发送数据（持续发送，每次间隔1秒）
    int i = 0;
    while (1)
    {
        // 生成随机配置数据
        start_atomic_0817_initialize_configuration_service_InitConfigInput data = generate_random_config_data();

        // 发送数据
        rc = dds_write(writer, &data);
        if (rc != DDS_RETCODE_OK)
        {
            std::cerr << "错误：dds_write失败，原因：" << dds_strretcode(-rc) << std::endl;
            LogClient::getInstance().logError("dds_write失败，原因：" + std::string(dds_strretcode(-rc)));
            free_config_data(data);
            cleanup();
            return EXIT_FAILURE;
        }

        // 打印发送的信息
        std::string info = "已发送配置服务数据（第" + std::to_string(i + 1) + "次）：\n";
        info += "  配置文件路径：" + std::string(data.config_file_path) + "\n";
        info += "  运行模式：" + std::string(data.run_mode) + "\n";
        info += "  日志启用状态：" + std::string(data.enable_logging ? "启用" : "禁用");

        std::cout << "==============================" << std::endl;
        std::cout << info << std::endl;
        std::cout << "==============================" << std::endl;
        LogClient::getInstance().logInfo(info);

        // 释放当前数据的字符串内存
        free_config_data(data);

        // 间隔1秒发送
        i++;
        dds_sleepfor(DDS_SECS(1));
    }

    // 清理资源
    cleanup();
    return EXIT_SUCCESS;
}